import React, { PureComponent } from 'react';
// 发送axios
import Axios from 'axios';
// 引入接口
import { webSite } from '../../website';
// 引入样式
import './scss/Upload.scss';
import { Button, message } from 'antd';
// 引入点击复制到粘贴板的办法
import copy from 'copy-to-clipboard';
export default class UploadCla extends PureComponent {
  constructor() {
    super();
    this.state = {
      // 图片上传之后的网络地址
      link: '',
      // 图片的Base64码
      Base64: 'data:image/jpg;base64,',
      // 图片的后缀
      strImg: 'jpg',
      // 上传图标与图片切换
      isImgLink: false,
    };
  }

  gen_base64 = () => {
    const _this = this;
    let file = document.getElementById('upload_file').files[0];
    // 判断图片大小
    let size = '';
    size = (file.size / 1024).toFixed(2);
    if (size >= 10240) {
      message.info({ content: '图片不要超过10MB', className: 'bulletChatMessage' });
      return;
    }
    if (file !== undefined) {
      // 获取上传的图片元素
      let index = file.type.lastIndexOf('/');
      let str = file.type.substring(index + 1, file.type.length); // 正则判断图片后缀
      let r = new FileReader(); //本地预览
      r.readAsDataURL(file); //Base64
      r.onload = function () {
        // 图片上传完成
        _this.setState({
          // 存储base64码
          Base64: r.result,
          // 存储图片后缀
          strImg: str,
          // 显示图片
          isImgLink: true,
          // 切换按钮
          isBtn: false,
        });
      };
    }
  };
  // 上传文件的点击事件
  clickFile = () => {
    // 调起上传文件
    let file = document.getElementById('upload_file');
    file.click();
  };

  // 把图片的base64码上传到后端服务器
  fileBtn = () => {
    if (this.state.isImgLink) {
      setTimeout(message.loading('高清壁纸上传中.....', 0), 600);
      const _this = this;
      let { Base64, strImg } = this.state;
      Axios.create({
        baseURL: `${webSite}:3003`,
      })
        .post('/upload', { image: Base64, name: strImg })
        .then((err) => {
          if (err.data.code === 'P0001') {
            _this.setState({
              link: err.data.link,
              isBtn: true,
            });
          }
        });
    } else {
      message.info({ content: '请先选择一张图片', className: 'bulletChatMessage' });
    }
  };
  // 再来一个
  eler = () => {
    this.setState({
      Base64: '',
      isImgLink: false,
      isBtn: false,
    });
  };
  // 首页文字点击
  BtnCopy = () => {
    if (copy(this.state.link)) {
      message.success({ content: '网址已复制到粘贴板', className: 'bulletChatMessage' });
    } else {
      message.error({ content: '您的设备不支持自动复制', className: 'bulletChatMessage' });
    }
  };

  render() {
    let { strImg, Base64, isImgLink, isBtn } = this.state;
    // 去掉base64的开头
    let base64Img = Base64.replace(/^data:image\/\w+;base64,/, '');
    let link = `data:image/${strImg};base64,${base64Img}`;
    return (
      <div className="upload">
        {/* 上传图标 */}
        {isImgLink ? (
          <img src={link} alt="预览图" className="upload_zhanshi" />
        ) : (
          <div className="upload_top" onClick={this.clickFile}>
            <span className="upload_top_left"></span>
            <span className="upload_top_right"></span>
          </div>
        )}
        <input
          accept="image/*"
          name="upimage"
          id="upload_file"
          type="file"
          onChange={this.gen_base64}
          style={{ display: 'none' }}></input>
        {/* 上传按钮 */}
        {isBtn ? (
          <Button onClick={this.eler} className="upload_btn">
            再来一个
          </Button>
        ) : (
          <Button onClick={this.fileBtn} className="upload_btn">
            上传
          </Button>
        )}
        {/* 网址展示功能 */}
        {isBtn ? (
          <div className="upload_button">
            <span>图片已转换为网络地址：</span>
            <a href={this.state.link}>{this.state.link}</a>
            <img
              src={require('../translate/image/copylianjie.png')}
              alt="复制"
              onClick={this.BtnCopy}
              className="upload_button_delete"
            />
          </div>
        ) : (
          ''
        )}
      </div>
    );
  }
}
